﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using StructureMap;

namespace DBMigrator.Core.Execution
{
    public class MigrationLocator : IMigrationLocator
    {
        private readonly Assembly assemblyContainingMigrations;

        public MigrationLocator(Assembly assemblyContainingMigrations)
        {
            this.assemblyContainingMigrations = assemblyContainingMigrations;
        }

        public IList<IExecutableMigration> GetMigrationsSatisfying(Func<MigrationAttribute, bool> condition)
        {
            return (from type in assemblyContainingMigrations.GetTypes()
                    let attributes = type.GetCustomAttributes(typeof (MigrationAttribute), false)
                    let migrationAttribute = (MigrationAttribute) attributes[0]
                    where attributes.Length > 0 && condition(migrationAttribute)
                    select ObjectFactory.GetInstance<IExecutableMigration>()
                        .Initialize(migrationAttribute, type))
                .ToList();
        }
    }
}
